import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:open_file/open_file.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'dart:io';

class AppVersionPage extends StatefulWidget {
  @override
  _AppVersionPageState createState( ) => _AppVersionPageState();
}
class _AppVersionPageState extends State<AppVersionPage> {
  @override
  void initState( ) {
    super.initState();
    this._getPackgeInfo();
    this._getAppPath();
//    this._downLoad();
  }
  ///获取版本号
  _getPackgeInfo( ) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String appName = packageInfo.appName;
    String packageName = packageInfo.packageName;
    String version = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;

    print("appName:$appName");
    print("packageName:$packageName");
    print("version:$version");
    print("buildNumber:$buildNumber");
  }

  ///获取路径 获取文件存储路径
  _getAppPath( ) async {
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;
    var directory = await getExternalStorageDirectory();
    String storageDirectory = directory.path;
    print("tempPath:$tempPath");
    print("appDocDir:$appDocPath");
    print("StorageDirectory:$storageDirectory");
  }

  ///下载打开文件
  _downLoad( ) async {
      final directory = await getExternalStorageDirectory();
      String _localPath = directory.path;
      ///await FlutterDownloader.initialize();
      /// show download progress in status bar (for Android) openFileFromNotification: true,
      ///click on notification to open downloaded file (for Android) );
      final taskId = await FlutterDownloader.enqueue(
          url: "http://www.ionic.wang/jdshop.apk",
          /// _getAppPath获取的StorageDirectory（只有这个能存储成功）
          savedDir: _localPath,
          ///显示进度
          showNotification: true,
          ///下载完后打开
          openFileFromNotification: true
      );
      ///下载进度
      FlutterDownloader.registerCallback((id,status,progress){
        print(status);
        print(progress);
      });
      ///打开文件
      OpenFile.open("$_localPath/jdshop.apk");
  }

  @override
  Widget build( BuildContext context ) {
    return Scaffold(
      appBar: AppBar(
        title: Text("检查版本升级"),
      ),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.file_download),
          onPressed: () async{
//            await FlutterDownloader.initialize();
//            this._downLoad();
          }),
    );
  }
}
